<?php


class School_model extends MY_Model {
	
	
	
	
	
	/**
	 * Constructor
	 */
	function School_model() {
		parent::__construct();
	}

	
	
	
	
	
	/**
	 * Get the information about page layout
	 */
	public function getLayoutInfo() {
		
		// path location of the web site
		$data['base_url']				= $this->config->item('base_url');
		
		// create the links to translate the page
		$switch_lang				= 	anchor($this->lang->switch_uri('en'),'en')." | ";
		$switch_lang				.= 	anchor($this->lang->switch_uri('pt'),'pt');
		$data['switch_lang']		= 	$switch_lang;
		
		// load the content text data ( all data is loaded ... it doesnt look the perfect solution ... find another one :0) )
		$data['text_main']			= $this->lang->line('school.text.main');
		$data['text_lnk1']			= $this->lang->line('school.text.lnk1');
		$data['text_lnk2']			= $this->lang->line('school.text.lnk2');
		$data['text_lnk3']			= $this->lang->line('school.text.lnk3');
		
		// ... more data
		$data['website_title']		= 'Radical Booking';
		$data['title']		 		= 'School';
		$data['login']				= anchor("School/logout","logout")." ".$this->ion_auth->get_user()->email;
		$data['subtitle'] 			= $this->lang->line('school.text.subtitle');
		$data['footer'] 			= '� copyright Softingal';
		
		return $data;
	}

	
	
	
	
	
	
	
	
	/**
	 * Get offer's 
	 * Options: Optional Values
	 * ------------------------
	 * id				- id of the offer 			(int)
	 * active			- if it is active or not 	('yes'/'no')
	 * name				- name of the offer			(varchar)
	 * available		- true/false (boolean) or 'both' if this option is omited 		
	 * datatype			- type of data to retrieve	(varchar) array/json/jtable
	 * @param array $options
	 * @return $data
	 */
	public function getOffer($options) {
		
		$dataTypeJSON 	= 'json';	// normal JSON format
		$dataTypeARRAY	= 'array';	// data is stored in an ARRAY
		$dataTypeJTABLE	= 'jtable';	// data formated for JTABLE 
		
		// who is asking for this?
		$user_id = $this->ion_auth->get_user()->id;
		
		// default fields
		$options = $this->_default(
		array(
			'datatype' => 'array',
		), $options);
		
		// validate option fields here ...
		
		// selection
		if ($options['datatype'] == $dataTypeJTABLE)
			$this->db->select('*');
		else {
			$this->db->select('id');
			$this->db->select('name');
			$this->db->select('remainingClasses');
			$this->db->select('numberOfClasses');
		}
		
		$this->db->from('offer');
		
		// only show offers of the current logged in user
		$this->db->where('users_id',$user_id);
		
		// optional conditions
		if (isset($options['id']))
			$this->db->where('id',$options['id']);
		if (isset($options['active']))
			if ($options['active'] == 'yes')
				$this->db->where('active',1);
			else if ($options['active'] == 'no')
				$this->db->where('active',0);
		if (isset($options['name']))
			$this->db->where('name',$options['name']);
		if (isset($options['available']))
			if ($options['available'] == true)
				$this->db->where('remainingClasses >',0);
			else if ($options['available'] == false)
				$this->db->where('remainingClasses',0);
		
		// get the data if exists
		$query = $this->db->get();
		
		// no data? return an empty json object
		if ($query->num_rows() == 0) {
			return false;
			//return '{ "Result":"OK", "Records":[]}';
		}
		
		// return only one record if 'id' field is set
		if (isset($options['id']))
			if ($options['datatype'] == $dataTypeARRAY )
				return $query->row(0);
			else if ($options['datatype'] == $dataTypeJSON)
				return json_encode($query->row(0)/*,JSON_NUMERIC_CHECK*/); 	// ... flag to preserve int fields
		
		// return one or more records
		if ($options['datatype'] == $dataTypeARRAY)
			return $query->result();
		else if ($options['datatype'] == $dataTypeJSON)
			return json_encode($query->result()/*,JSON_NUMERIC_CHECK*/);	// ... flag to preserve int fields
		else if ($options['datatype'] == $dataTypeJTABLE) {
			$result = $query->result();
			$arr 	= array("Result"=>"OK","Records"=>$result,"TotalRecordCount"=>$query->num_rows());
			$json	= json_encode($arr);
			return $json;				
		}
	}
	
	/**
	 * Create Offer and return that offer in JSON format
	 */
	public function addOffer($post) {
		
		// set the id of the corrente school user
		$this->db->set('users_id',$this->ion_auth->get_user()->id);
		
		// set all data fields passed in the POST
		$this->db->set($post);
		
		// insert data 
		$this->db->insert('offer');
		
		// select the last inserted record table offer 
		$query 		= $this->db->query("select * from offer where id=(select max(id) from offer);");
		
		// the result will be fetched into the first indice of this array (the previous select returns only one row)
		$data_array = $query->result();

		// format the array ... "Record" should only have one registry, in this case the first and only array index
		$final_arr 	= array("Result"=>"OK","Record"=>$data_array[0]);
		
		// translate to json format
		$json 		= json_encode($final_arr); 	
		
		// return the last offer inserted to DB in json format
		return $json;
	}
	
	/**
	 * Delete Offer
	 * @param Int $id of the offer to be deleted 
	 */
	public function deleteOffer($id) {
		$tmp_where  = $this->db->where('id',$id);
		$tmp_delete = $this->db->delete('offer');
	}
	
	/**
	 * Update Offer
	 * @param array $post array with all fields to be updated
	 */
	public function updateOffer($post) {
		$this->db->update('offer',$post,array('id'=>$post['id']));
	}	
	
	
	
	
	
	
	
	/**
	 * Create a new record in the db table 'extra'
	 * @param array $post array with all extra fields to be inserted 
	 * @return object return false if no data was inserted or the record inserted in jtable json format 
	 */
	public function createExtra($post) {
		
		$users_id = $this->ion_auth->get_user()->id;
		
		$this->db->set('users_id',$users_id);

		$succ = $this->db->insert('extra',$post);
		
		if ($succ) {
			$this->db->select_max('id');
			$query = $this->db->get('extra');
			$row = $query->row();
			$extraId = $row->id;
			return $this->readExtra($extraId);
		}
		else {
			return false;	
		}
	}
	
	
	
	/**
	 * Get extra items in jtable format 
	 * @param id $id - the extra identification if we only want one record ('null' for all extras)
	 * @param offerId $offerId - The offer identification if we only want extras associated to a specific offer
	 */
	public function readExtra($id = null,$offerId = null) {
		
		$users_id = $this->ion_auth->get_user()->id;
		
		$this->db->select('*');
		$this->db->from('extra');
		
		if ($id != null)
			$this->db->where('id',$id);
		
		$this->db->where('users_id', $users_id);
		
		if ($offerId != null) {
			$this->db->join('extra_offer','extra_offer.extra_id = extra.id');
			$this->db->where('offer_id', $offerId);
		}
		
		$query = $this->db->get();
			
		if ($query->num_rows() == 0)
			return false;
			
		$rows = $query->result(); 
		
		$jTableResult['Result'] = 'OK';
		
		// if 'id' is set ... we only want the first and only record
		if ($id)
			$jTableResult['Record'] 	= $rows['0'];
		else
			$jTableResult['Records'] 	= $rows;
		
		return json_encode($jTableResult);
	}
	
	public function updateExtra($post) {
		$res = $this->db->update('extra',$post,array('id'=>$post['id']));
		return $res;
	}
	
	public function deleteExtra($id) {
		$this->db->where('id',$id);
		$res = $this->db->delete('extra');
		return $res;
	}
	
		
		
	
	
	
	
	

	/**
	 * Options: Optional Values
	 * ---------------
	 * id - only this event
	 * offer_id - event associated to this offer
	 * start - from this date ...
	 * end - to this date
	 * @param array $options with conditional optional values
	 * @return array $result 
	 */
	public function getEvent($options) {
		
		// who is asking for this?
		$user_id = $this->ion_auth->get_user()->id;
		
		// make the selection
		$this->db->select('
			schedule.id 				as id, 
			offer.name 					as title, 
			schedule.start				as start, 
			schedule.end				as end,
			fullcalevent.editable		as editable,
			fullcalevent.allDay			as allDay,
			offer.color					as color,
			offer.bgColor				as bgColor,
			fullcalevent.borderColor			as borderColor,
			offer.textColor		as textColor'
		);
		
		// perform the join with 3 tables (offer, schedule, fullcalevent)
		$this->db->from('schedule');
		$this->db->join('offer','offer.id = schedule.offer_id');
		$this->db->join('fullcalevent','fullcalevent.schedule_id = schedule.id');
		
		// only the events of the current logged in user will be displayed
		$this->db->where('users_id',$user_id);
		
		// set optional conditions
		if (isset($options['id']))
			$this->db->where('id',			$options['id']);
		if (isset($options['offer_id']))
			$this->db->where('offer_id',	$options['offer_id']);
		if (isset($options['start']))
			$this->db->where('start >',		$options['start']);
		if (isset($options['end']))
			$this->db->where('end <',		$options['end']);

		$query = $this->db->get();
		
		if ($query->num_rows() == 0)
			return false;
		
		if (isset($options['id']))
			return $query->row(0);
		else 
			return $query->result_array();
	}

	
	
	
	
	
	
	
	
	
	/**
	 * Create an Event record in 'schedule' and 'fullcalevent' table
	 * ----------------------------------------------
	 * Options: Required Values
	 * ---------------
	 * offer_id		- id of the offer		(int)					
	 * eventStart	- when the event starts (datetime)	
	 * eventEnd		- when the event ends	(datetime)	
	 * 
	 * Options: Optional Values
	 * ---------------
	 * editable (tinyint), allDay(tinyint), color(varchar), bgColor(varchar), 
	 * borderColor(varchar), textColor(varchar)
	 *  
	 * @param array $options
	 * @return $id of the event if it was created, or 'false' if it was not created
	 */
	public function addEvent($options) {
		
		// required fields
		if (!$this->_required(array('offer_id','eventStart','eventEnd'), $options))
			return false;
		
		// default values
		$options = $this->_default(
			array(
				'allDay'	=>0,
				'editable'	=>1,
				'color'=>'blue',
			), 
		$options);
		
		// set data to be added 
		$this->db->set('offer_id',	$options['offer_id']);
		$this->db->set('start',		$options['eventStart']);
		$this->db->set('end',		$options['eventEnd']);
		
		// table name
		$this->db->insert('schedule');

		// get the 'id' of the added event
		$id = $this->db->insert_id();
		
		// if the event was created 
		if ($id) {
			
			// clear previous operations
			$this->db->flush_cache();
			
			// decrement one value to the number of available classes 
			$this->db->select('remainingClasses');
			$this->db->from('offer');
			$this->db->where('id',$options['offer_id']);
			$query = $this->db->get();
			$row = $query->result();
			$remainingClasses = $row['0']->remainingClasses;
			$remainingClasses--;
			$this->db->flush_cache();
			$this->db->where('id',$options['offer_id']);
			$this->db->update('offer',array('remainingClasses'=>$remainingClasses));
			$this->db->flush_cache();
			
			// add data to fullcalevent
			$this->db->set('schedule_id',$id);
			if (isset($options['editable'])) 	$this->db->set('editable',		$options['editable']);
			if (isset($options['allDay']))		$this->db->set('allDay',		$options['allDay']);
			if (isset($options['color']))		$this->db->set('color',			$options['color']);
			if (isset($options['bgColor'])) 	$this->db->set('bgColor',		$options['bgColor']); 
			if (isset($options['borderColor'])) $this->db->set('borderColor',	$options['borderColor']); 
			if (isset($options['textColor'])) 	$this->db->set('textColor',		$options['textColor']); 
			$this->db->insert('fullcalevent');
		}
		
		// return the last record id added or false if no event was added 
		return $id; 
	}

	
	/**
	 * Delete Event
	 */
	public function deleteEvent() {
		
	}

	
	/**
	*
	* @param array $options
	* @return boolean $succ return TRUE if  updated, FALSE otherwise
	*/
	public function updateEvent($options) {
	
			
	}
	
	
	/**
	 * check if an event exists 
	 */
	public function isEvent($id) {
		
	}
	
	
	public function readReservation() {
		
		$user_id = $this->ion_auth->get_user()->id;
		
		$this->db->select('
			active, price, numberOfClasses,
			address, email, phone, birthday,
			date,
			reservation.id	as reservationId,
			offer.id		as offerId,
			client.id		as clientId,
			offer.name 		as offerName, 
			client.name 	as clientName
		');
		$this->db->from('reservation');
		$this->db->join('client','client.id = reservation.client_id');
		$this->db->join('offer','offer.id = reservation.offer_id');
		$this->db->where('offer.users_id',$user_id);
		$query = $this->db->get();
		$rows = $query->result();
		//$this->chromephp->log($rows);
		$dataTableResult['data'] = $rows;
		return json_encode($dataTableResult);
	}
	
	
	
	
	
	
	/**
	* Get all offers from the current school user
	*/
	public function old_getOffer() {
	
		// who is in?
		$user_id = $this->ion_auth->get_user()->id;
	
		// select all offers from the current school user
		$query = $this->db->query("select * from offer where users_id = '$user_id'");
	
		// array with selected rows
		$offer_arr = $query->result();
	
		// format the array to be delivered to jtable JSON format
		$final_arr = array("Result"=>"OK","Records"=>$offer_arr,"TotalRecordCount"=>$query->num_rows());
	
		// encode to JSON
		$offer_json = json_encode($final_arr);
	
		// return offers in JSON format
		return $offer_json;
	}
	
	
	
	
	/**
	*
	* Get all available offers. there is other function to get the offers ...
	* this one is to get offers to fill a dropdown list ... try later to merge these to functions...
	* @return JSON obj with 'id', 'name' and 'remainingClasses' of the available offers to be used in the schedule calendar
	*/
	public function old_getAvailableOffers() {
	
		// verificar se ha marcacoes
	
		// who is asking for this?
		$user_id = $this->ion_auth->get_user()->id;
	
		// make the selection
		$this->db->select('id, name, remainingClasses');
	
		// witch table?
		$this->db->from('offer');
	
		// condition ( current user, active and available offers )
		$this->db->where('users_id',$user_id);
		$this->db->where('active',1);
		$this->db->where('remainingClasses >',0);
	
		// run the query
		$query = $this->db->get();
	
		// return the json
		return json_encode($query->result());
	}
	
	
	

	
	/**
	 * @param array $defaults with fields and data that should be set to default if not present
	 * @param array $options where the default values must be placed
	 * @return array with the merged values
	 */
	private function _default($defaults, $options) {
		return array_merge($defaults, $options);
	}
	
	
	/**
	 * Checks if the array has all requiered fields
	 * @param array $required with the requiered fields
	 * @param array $data with the fields to be checked
	 * @return TRUE if the field exists FALSE otherwise
	 */
	private function _required($required, $data) {
		foreach ($required as $field) 
			if (!isset($data[$field]))
				return false;
		return true;
	}


	
	
	/**
	 * Flush data relative to Past Events.
	 * The field editable is set to '0' and the 'borderColor' is set to black 
	 * in the past events in order to avoid changes in these events.
	 * @param datetime $start 
	 * @param datetime $end
	 */
	public function flushPastEvents($start, $end) {
		
		// get current time (datetime)
		$now = date('Y-m-d H:i:s',time());
		
		// select 'id' ...
		$this->db->select('id');
		$this->db->from('schedule');
		$this->db->join('fullcalevent','fullcalevent.schedule_id = schedule.id'); // we need to join to get 'editable' column
		
		// .. in the given range
		$this->db->where('start >'	, $start);
		$this->db->where('end <'	, $end);
		
		// ... and before the actual date
		$this->db->where('start <'	, $now);
		
		// ... and only those fields who are editable.
		$this->db->where('editable',1);
		
		// get results
		$query = $this->db->get();
		$row = $query->result();
		
		// data to update
		$data = array(
			'editable' 		=> 0,
			'borderColor' 	=> 'black'
		);
		
		// update all items with previous data ... 
		foreach ($row as $item) {
			$this->db->update('fullcalevent',$data,array('schedule_id'=>$item->id));
		}
	}

	
	
	
	
	
	
	/**
	 * Flush Offer Data
	 * Reset the remainingClasses field in all offers that dont have
	 * any future schedules so these offers can be available again.
	 */
	public function flushOffers() {
		
		// id of the current user
		$user_id = $this->ion_auth->get_user()->id;
		
		// current time in datetime format
		$now = date('Y-m-d H:i:s',time());
		
		// offer's beeing used above the current date
		$inUseOfferID = array();
		
		// all offer ID's of the current user
		$allOfferID = array();
		
		// get offer id's beeing used above current date
		$this->db->select('offer.id');
		$this->db->from('offer');
		$this->db->join('schedule','schedule.offer_id = offer.id');
		$this->db->where('end >',$now);
		$query = $this->db->get();
		$row = $query->result();
		foreach ($row as $item) {
			array_push($inUseOfferID, $item->id);
		}
		$inUseOfferID = array_unique($inUseOfferID);
		
		// clear previous db results
		$this->db->flush_cache();
		$query = null; $row = null;
		
		// get all offers id's
		$this->db->select('id');
		$this->db->from('offer');
		$this->db->where('users_id',$user_id);
		$query = $this->db->get();
		$row = $query->result();
		foreach ($row as $item) {
			array_push($allOfferID, $item->id);
		}
		$allOfferID = array_unique($allOfferID);
		
		// get the array with offer id's to update 
		$toUpdateOfferID = array_diff($allOfferID, $inUseOfferID);
		//$this->chromephp->log($allOfferID);
		//$this->chromephp->log($inUseOfferID);
		$this->chromephp->log($toUpdateOfferID);
		
		// clear previous db results
		$this->db->flush_cache();
		$query = null; $row = null;
		
		// reset the remainingClasses field only if necessary 
		if (!empty($toUpdateOfferID)) {
// 			$this->firephp->log('empty fields');
// 			$this->chromephp->log('empty fields');
			$this->db->select('id, numberOfClasses, remainingClasses');
			$this->db->from('offer');
			$this->db->where_in('id',$toUpdateOfferID);
			$query = $this->db->get();
			$row = $query->result();
			foreach ($row as $item) {
				$this->db->where('id',$item->id);
				// reset 'remainingClasses' with the value 'numberOfClasses' ... 
				// and reset the participant number to 0 ... check if it works
				$this->db->update('offer', array('remainingClasses'=>$item->numberOfClasses,'part'=>0), array('id'=>$item->id));
			}
		}
		else {
			
		}
	}
	
	
	
	
	
	
	public function tmp() {
		//echo 'hello';
		
		//echo $this->ion_auth->get_user()->id;
		$this->firephp->log($this->ion_auth->get_user()->id);
		
	}
	
	
	
	
	
	
}